package com.yanfan.modbus.frame;

import com.yanfan.common.ByteUtil;
import com.yanfan.modbus.ModbusUtils;
import com.yanfan.modbus.code.FunctionCode;
import com.yanfan.modbus.exception.ModbusTransportException;
import com.yanfan.modbus.frame.abs.ModbusRequest;
import io.netty.buffer.ByteBuf;


public class WriteCoilsRequest extends ModbusRequest {
    private int startOffset;
    private int numberOfBits;
    private byte[] data;


    public WriteCoilsRequest(int slaveId, int startOffset, boolean[] bdata) throws ModbusTransportException {
        super(slaveId);
        this.startOffset = startOffset;
        numberOfBits = bdata.length;
        data = ByteUtil.convertToBytes(bdata);
    }

    public WriteCoilsRequest(int slaveId) throws ModbusTransportException {
        super(slaveId);
    }


    @Override
    public void validate() throws ModbusTransportException {
        ModbusUtils.validateOffset(startOffset);
        ModbusUtils.validateNumberOfBits(numberOfBits);
        ModbusUtils.validateEndOffset(startOffset + numberOfBits - 1);
    }


    @Override
    protected void writeRequest(ByteBuf queue) {
        queue.writeShort(startOffset);
        queue.writeShort(numberOfBits);
        queue.writeByte(data.length);
        queue.writeBytes(data);
    }


    @Override
    public byte getFunctionCode() {
        return FunctionCode.WRITE_COILS;
    }


    @Override
    protected void readRequest(ByteBuf queue) {
        startOffset = queue.readUnsignedShort();
        numberOfBits = queue.readUnsignedShort();
        data = new byte[queue.readUnsignedByte()];
        queue.readBytes(data);
    }
}
